package com.dwj.auto.comment.common.wechat;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author: dangweijian
 * @description: 微信接入
 * @create: 2020-09-17 17:03
 **/
@Slf4j
@RestController
@RequestMapping("/wechat")
public class AccessWeChatController {

    @Resource
    private WxMpService mpService;

    @ResponseBody
    @RequestMapping("/access")
    public String verify(HttpServletRequest request,
                         @RequestParam(value = "signature", required = false) String signature,
                         @RequestParam(value = "timestamp", required = false) String timestamp,
                         @RequestParam(value = "nonce", required = false) String nonce,
                         @RequestParam(value = "echostr", required = false) String echostr) {
        if (!mpService.checkSignature(timestamp, nonce, signature)) {
            log.info("微信接口认证失败：signature:[" + signature + "]，timestamp:[" + timestamp + "]，nonce:[" + nonce + "]，echostr:[" + echostr + "]");
            return "接口验证失败！";
        }
        //消息验证
        if (StringUtils.isNotBlank(echostr)) {
            return echostr;
        }
        //接收消息
        return new MessageRecipient(request, timestamp, nonce).execute();
    }
}
